package android.gpsmessenger;

import java.util.Iterator;

import android.os.Bundle;
import android.app.ListFragment;

import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;

import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class TripProfileFragment extends ListFragment
{
	private ContactManager contactManager ;
	private ContactList contacts;
	private ContactList selectedContacts;
	private TripManager tripManager;
	private TripList trips;
	private Trip trip ; //= null;

	private ContactAdapter helpAdapter, friendAdapter;
	private ListView helpListView, friendListView;

	private String tripName = null;
	private boolean saveData = true;
	
	EditText trip_name_field ;
	EditText sos_phone_field ;
	
	public void onCreate (Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		
		contactManager = new ContactManager(getActivity());
		contacts = new ContactList();
		selectedContacts = new ContactList();
		
		tripManager = new TripManager(getActivity());
		trip = null;
		trips = new TripList();
		tripName = getActivity().getIntent().getStringExtra("name");
	}
		
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
	{
		inflater.inflate(R.menu.fragment_ok_cancel_menu, menu);
	}
	
	public void onResume() 
	{
		super.onResume();
		saveData = true;
		contacts = contactManager.load();
		
	    helpAdapter.setContacts(contacts.getHelpContacts().getContactList());
	    helpListView.setAdapter(helpAdapter);	
	    friendAdapter.setContacts(contacts.getFriendContacts().getContactList());
	    friendListView.setAdapter(friendAdapter);	
	    
		trips = tripManager.load();	    
		if (tripName != null) 
		{
			Trip trip = trips.getTrip(tripName);

			trip_name_field = (EditText) getActivity().findViewById(R.id.trip_name);
			sos_phone_field = (EditText) getActivity().findViewById(R.id.sos_phone);
			//CheckBox check_box = (CheckBox) getActivity().findViewById(R.id.contact_check_box);
			
			trip_name_field.setText(trip.getName());
			sos_phone_field.setText(trip.getContacts().getSOSContact().getPhone());	
		}
	}

	public void onPause() 
	{
	    super.onPause();

		if (saveData) 
		{	
			trip_name_field  = (EditText) getActivity().findViewById(R.id.trip_name);
			sos_phone_field  = (EditText) getActivity().findViewById(R.id.sos_phone);
			
			String name  = trip_name_field.getText().toString();
			String phone = sos_phone_field.getText().toString();

			LocationList prevLocations = null;
			if (tripName != null)
			{
				Trip trip = trips.getTrip(tripName);
				prevLocations = trip.getLocations();
				trips.removeTrip(tripName);
			}

			trip = new Trip(name);
			contacts.setSOSContact(new Contact("sos", phone));
			trip.setContactList(selectedContacts);
			Log.i("SelectedContacts", "SelectedContacts: " + selectedContacts);
			if(prevLocations != null)
			{
				Iterator<Location> locs = prevLocations.iterator();
				while(locs.hasNext())
				{
					trip.addLocation(locs.next());
				}
			}
			
			trips.addTrip(trip.getName(), trip);
			//Log.i("Trips", "Trips: " + trips);
			tripManager.save(trips);	
		}	    
	}	
		
	@Override
	public void onActivityCreated(Bundle savedInstanceState) 
	{
		super.onActivityCreated(savedInstanceState);
		getActivity().setContentView(R.layout.fragment_trip_profile);
		contacts = contactManager.load();
		
		helpListView  = (ListView)  getActivity().findViewById(R.id.helplistView);
		helpAdapter = new ContactAdapter(getActivity(), R.layout.multicheck_custom_row_view, contacts.getHelpContacts().getContactList());
	    helpListView.setAdapter(helpAdapter);
	    helpListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	    helpListView.setItemsCanFocus(false);
	    
		friendListView  = (ListView)  getActivity().findViewById(R.id.friendlistView);
		friendAdapter = new ContactAdapter(getActivity(), R.layout.multicheck_custom_row_view, contacts.getFriendContacts().getContactList());
	    friendListView.setAdapter(friendAdapter);
	    friendListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	    friendListView.setItemsCanFocus(false);
	    
	    helpListView.setOnItemClickListener(new OnItemClickListener() 
	    {
	        @Override
	        public void onItemClick(AdapterView<?> a, View v, int position, long id) 
	        {
	        	final SparseBooleanArray checkedItems = helpListView.getCheckedItemPositions();
                int checkedItemsCount = checkedItems.size();
                int checkedPosition;
                selectedContacts.getHelpContacts().clear();
                for (int i = 0; i < checkedItemsCount; ++i) 
                {
                   checkedPosition = checkedItems.keyAt(i);
                    if(checkedItems.valueAt(i))
                       selectedContacts.add(helpAdapter.getItem(checkedPosition));                	
                }
            }
        });
	    
	    friendListView.setOnItemClickListener(new OnItemClickListener() 
	    {
	        @Override
	        public void onItemClick(AdapterView<?> a, View v, int position, long id) 
	        {
	        	final SparseBooleanArray checkedItems = friendListView.getCheckedItemPositions();
                int checkedItemsCount = checkedItems.size();
                int checkedPosition;
                selectedContacts.getFriendContacts().clear();
                for (int i = 0; i < checkedItemsCount; ++i) 
                {
                    checkedPosition = checkedItems.keyAt(i);
                    if(checkedItems.valueAt(i))
                       selectedContacts.add(friendAdapter.getItem(checkedPosition));                    	
                }
            }
        });	   
    }
	
	public boolean onOptionsItemSelected (MenuItem item) 
	{
		switch (item.getItemId()) 
		{
		 	case R.id.menu_ok:
		 		if(validated()) 
		 		{
		 			saveData = true;
		 			getActivity().finish();
		 		} 
		 		else 
		 		{
		 			WarningDialog.showDialog(getActivity());
		 			//Toast.makeText(getActivity(), 
		 			//"You have missing or incorrect values in some form fieds!", Toast.LENGTH_SHORT).show();
		 		}
		 		break;
		 	case R.id.menu_cancel:
		 		saveData = false;
		 		getActivity().finish();
		 		break;
		 }
		return true;
	}	
	
	protected boolean validated() 
	{		  
		boolean validated = true;
		
		trip_name_field  = (EditText) getActivity().findViewById(R.id.trip_name);
		sos_phone_field  = (EditText) getActivity().findViewById(R.id.sos_phone);
		
		if (!Validate.hasText(trip_name_field)) validated = false;
		if (!Validate.hasText(sos_phone_field)) validated = false;
	
		return validated;
	}			

}
